from typing import Union, Tuple, Optional

import requests

from registry_client.inner_registry_http_client import InnerRegistryHttpClient
from registry_client.manifest import Manifest


class RegistryClient:
    def __init__(self,
                 host: str,
                 port: int,
                 use_tls: bool = False,
                 cert: Union[str, Tuple[str, str]] = None,
                 verify: bool = True,
                 authorization: str = None):
        protocol = 'https' if use_tls else 'http'
        base_url = f'{protocol}://{host}:{port}/v2'
        self.http_client = InnerRegistryHttpClient(base_url, cert=cert, verify=verify, authorization=authorization)

    def get_manifest(self, repository: str, tag: str, organization: Optional[str] = None) -> Manifest:
        if organization:
            endpoint = f'{organization}/{repository}/manifests/{tag}'
        else:
            endpoint = f'{repository}/manifests/{tag}'

        headers = {'Accept': 'application/vnd.docker.distribution.manifest.v2+json'}

        response = self.http_client.get(endpoint, headers=headers)

        if response.status_code != 200:
            raise Exception(f'Error getting manifest: {response.status_code} {response.text}')

        return Manifest.from_dict(response.json())
